﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElearningOUHv2.Models;
using ElearningOUHv2.DAL;
using System.IO;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Web.Security;

namespace ElearningOUHv2.Controllers
{
    public class EmneController : Controller
    {
        private ElearningContext db = new ElearningContext();

        public ActionResult IndexAdmin()
        {
            return View(db.Emne.ToList());
        }

        [HttpPost]
        public ActionResult IndexAdmin(string emner)
        {
            Session["spgEmne"] = emner;
            return RedirectPermanent("/adminspg/index");
        }

        public ActionResult IndexSpg()
        {
            if (User.Identity.IsAuthenticated)
                ViewBag.SvaretList = SvarList();
            return View(db.Emne.ToList());
        }

        [HttpPost]
        public ActionResult IndexSpg(string emner)
        {
            Session["spgEmne"] = emner;
            return RedirectPermanent("/test/index");
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Emne emne)
        {
            db.Emne.Add(emne);
            db.SaveChanges();
            return RedirectPermanent("IndexAdmin");
        }

        public string[] SvarList()
        {
            //// Henter liste med svar fra databasen
            //List<BrugersvarForSpg> spørgsmål = db.BrugersvarForSpg.ToList();
            // Finder bruger id.
            Guid BrugerId = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
            // Laver liste med svaret
            List<string> Svaret = new List<string>();
            List<Svar> svarListe = (from svarItem in db.Svar
                                    where svarItem.userId == BrugerId
                                    select svarItem).ToList();

            List<Emne> emner = db.Emne.ToList();

            foreach (Emne E in emner)
            {
                int temp = (from svarItem in svarListe
                            from spgItem in E.spgList
                            where spgItem == svarItem.spg && svarItem.userId == BrugerId
                            select svarItem).Count();
                            
                int temp2 = E.spgList.Count();
                Svaret.Add("Der er svaret " + temp + " af " + temp2 + " spørgsmål");

            }
            return Svaret.ToArray();

        }
    }
}
